from django.contrib.auth.models import User
from apps.accounts.models import UserProfile


def create_user_with_profile(username, email, first_name, role, college_name='', password='123456'):
    """创建用户并关联用户信息"""
    user = User.objects.create_user(
        username=username,
        email=email,
        first_name=first_name,
        password=password
    )
    
    UserProfile.objects.create(
        user=user,
        role=role,
        college_name=college_name
    )
    
    return user


def get_user_role(user):
    """获取用户角色"""
    try:
        return user.userprofile.role
    except UserProfile.DoesNotExist:
        return None


def is_admin(user):
    """检查是否为管理员"""
    try:
        return user.userprofile.is_admin
    except UserProfile.DoesNotExist:
        return False


def is_college_user(user):
    """检查是否为二级学院使用者"""
    try:
        return user.userprofile.is_college_user
    except UserProfile.DoesNotExist:
        return False


def can_manage_projects(user):
    """检查是否可以管理项目"""
    return is_admin(user)


def can_manage_subprojects(user):
    """检查是否可以管理子项目"""
    return is_admin(user) or is_college_user(user)


def can_edit_subproject_status(user):
    """检查是否可以编辑子项目状态"""
    return is_admin(user)


def can_delete_subproject(user, subproject):
    """检查是否可以删除子项目"""
    if is_admin(user):
        return True
    if is_college_user(user) and subproject.created_by == user:
        return True
    return False